/**
* Created by Jancheng on 2017/9/22.
*轻手记富文本输入框
*/
<template>
  <div class="qsj-editor" :class="flexClass">
    <div class="qsj-editor-input qsj-user-modify"   v-qsj-focus="isFocus"  contenteditable="true" :style="{minHeight:minHeight+'rem'}"  ref="qsjinput" @input="changeInput" @keydown="inputKeyDown($event)"  @paste="pasteLister($event)" :class="{'qsj-user-modify-readonly':readonly}" :placeholder="placeholder">
    </div>
    <div class="qsj-counter" :class="{'qsjWaring':currentTotal>maxInput?true:false}" v-show="showCounter && maxInput">
      <span>{{currentTotal}}</span>/{{maxInput}}
    </div>
    <input v-model="currentValue" v-show="false">
  </div>
</template>
<script type="text/ecmascript-6">
  import tools from '@/utils/common';
  export default{
    name:'qsjeditor',
    //自定义聚焦指令
    directives: {
      'qsj-focus':function (el,binding) {
        if(binding.value){
          el.focus();
        }else{
          el.blur();
        }
      }
    },
    props:{
      //是否统计总数
      showCounter:{
        type:Boolean,
        default:true,
      },
      //是否聚焦
      isFocus:{
        type:Boolean,
        default:true
      },
      //输入总数位置，当show-counter为true显示 top:上 bottom:下 left ：左，right ：右
      counterPosition:{
        type:String,
        default:'right',
      },
      //最大输入数据
      maxInput:{
        type:Number,
        default:500,
      },
      //最小高度
      minHeight:{
        type:Number,
        default:.5
      },
      //提示
      placeholder: {
        type:String,
        default:"请填写内容"
      },
      //是否只可读
      readonly: {
        type:Boolean,
        default:false
      },
      value:{
        type:String,
        default:"",
      },
      id:{
        type:String,
        default:"qsj-editor-text-area",
      }
    },
    data(){
      return{
        currentHtml:"",
        //双向绑定值
        currentValue:this.value,
        //输入数据总和
        currentTotal:0,
        //1：模型数据驱动--->内层数据 2：内层数据--->驱动模型数据
        direct:1,
        //上次触发:B大,S小
        lastestWaringEmit:'B',
      }
    },
    created (){
      this.currentValue = this.value
    },
    watch:{
      //监听内层数据改变
      currentValue(){
        this.currentHtml=this.currentValue;
        console.info("数据修改监听========"+this.currentHtml);
        if(this.direct==1){
          $(this.$refs.qsjinput).html(this.currentHtml);
        }
        //修正驱动方向
        this.direct=1;
        this.$emit('input', this.currentValue);
        this.$emit('on-change', this.currentValue);
      },
      //监听模型数据
      value (val) {
        this.direct=1;
        this.currentValue = val;
      },
    },
    mounted:function(){
      this.$nextTick(function () {
        this.currentHtml=this.currentValue;
        if(this.direct==1){
          $(this.$refs.qsjinput).html(this.currentHtml);
          this.currentTotal=this.$refs.qsjinput.innerText.length;//设置数据量
        }
      })
    },
    methods:{
      //输入框改变监听
      changeInput(){
        let vm=this;
        if(this.$refs.qsjinput.innerHTML=="<br>"){
          $(this.$refs.qsjinput).empty();
          this.currentValue="";
        }else{
          //ios 首次输入后，光标位置在开始处的BUG
          if(vm.currentValue==''){
            vm.currentHtml=vm.$refs.qsjinput.innerHTML;
            vm.currentValue=vm.currentHtml;
          }else{
            //选区设置后，处理换行
            setTimeout(function () {
              vm.currentHtml=vm.$refs.qsjinput.innerHTML;
              vm.currentValue=vm.currentHtml;
            },25)
          }
        }
        this.direct=2;
        this.currentTotal=this.$refs.qsjinput.innerText.length;//设置数据
        //触发父组件方法
        this.emitParentMethods();
      },
      //键盘keyDown监听
      inputKeyDown(event){
        var key = event.keyCode;
        //清空处理placeholder数据
        if ((this.currentHtml.length== 0 || $(this.$refs.qsjinput).text()=='') && key === 8) {
          $(this.$refs.qsjinput).empty();
          this.currentHtml='';
          this.currentValue='';
        }
        if (key===13) {
          let vm=this;
          setTimeout(function () {
            var select = window.getSelection();//获取选中节点
            var range =select.getRangeAt(0);//获取选区内容
            var node2 = range.createContextualFragment("<br><br>");
            if(tools.getBrowserVersions().ios){//ios会自动加载br换行
              node2 = range.createContextualFragment("<br>");
            }
            var of=node2.firstChild;
            var o = node2.lastChild;
            var node =document.createElement("br");//创建换行节点
            node.setAttribute("type", "qsj_moz");
            range.deleteContents();
            range.insertNode(node);//在选区中插入节点
            range.insertNode(node2);//在选区中插入节点
            range.setStartAfter(o);//移动光标设置该区域的开始节点为此node节点之前
            range.setEndAfter(o);//移动光标设置该区域的节点节点为此node节点之后
            //防止选取失效
            if(tools.getBrowserVersions().ios){//ios选取失效
              setTimeout(function () {
                o.setAttribute("tag", "qsj_add");
                of.setAttribute("tag", "qsj_br");
              },30);
            }else{
              o.setAttribute("tag", "qsj_add");
              of.setAttribute("tag", "qsj_br");
            }
            range.collapse(!1);//移动到尾部
            select.removeAllRanges();
            select.addRange(range);
            var s = $(vm.$refs.qsjinput).find("br[type='qsj_moz']");
            s.length > 0 && s.remove();
            $(vm.$refs.qsjinput).append('<br type="qsj_moz">');
          },10)
        }
      },
      //粘贴监听
      pasteLister(e){
        let beforeText =e.clipboardData.getData('text/plain');//获取粘贴板数据
        let html=this.plainHtml(beforeText);//处理粘贴板数据
        let historyHtml=$(this.$refs.qsjinput).html();
        let vm=this;
        setTimeout(function () {
          $(vm.$refs.qsjinput).html(historyHtml+html);//bug待研究
          let dom =$(vm.$refs.qsjinput)[0];//获取document对象
          let select = window.getSelection();//获取选区
          let range = document.createRange();//创建选区
          range.selectNodeContents(dom);//指定起点和终点
          range.collapse(false);//移动尾部
          select.removeAllRanges();
          select.addRange(range);
          return false;
        },200);
      },
      //html比较处理
      plainHtml:function (e) {
        let t = !(arguments.length > 1 && void 0 !== arguments[1]) || arguments[1];
        return e ? t ? e.replace(/&/gi, "&#38;").replace(/[<]/gi, "&#60;").replace(/[>]/gi, "&#62;").replace(/\r\n/gi, "<br/>").replace(/\n/gi, "<br/>").replace(/ /gi, "&nbsp;") : e.replace(/&/gi, "&#38;").replace(/[<]/gi, "&#60;").replace(/[>]/gi, "&#62;") : ""
      },
      //触发父节点方法
      emitParentMethods:function () {
        if(this.showCounter&&this.maxInput){
          let id=this.id;
          if(this.currentTotal>this.maxInput&&this.lastestWaringEmit=='S'){
            this.lastestWaringEmit='B';
            let obj={"waring":true,'id':id};
            this.$emit("getQsjEditorWaringInput",obj);
          }
          if(this.currentTotal<=this.maxInput&&this.lastestWaringEmit=='B'){
            this.lastestWaringEmit='S';
            let obj={"waring":false,'id':id};
            this.$emit("getQsjEditorWaringInput",obj);
          }
        }
      }
    },
    computed:{
      flexClass () {
        let returnClass="qsj-editor-left";
        switch (this.counterPosition){
          case 'top':
            returnClass="qsj-editor-top";
            break;
          case 'bottom':
            returnClass="qsj-editor-bottom";
            break;
          case 'right':
            returnClass="qsj-editor-right";
            break;
          default :
            returnClass="qsj-editor-left";
            break;
        }
        return returnClass;
      }
    }
  }
</script>
<style scope>
  .qsj-user-modify{
    user-modify:read-write-plaintext-only;
    -webkit-user-modify: read-write-plaintext-only;
    -moz-user-modify:read-write-plaintext-only;
  }
  .qsj-user-modify-readonly{
    user-modify:read-only;
    -webkit-user-modify:read-only;
    -moz-user-modify:read-only;
  }
  .qsj-editor{
    display: flex;
    width: 100%;
  }
  .qsj-editor-bottom{
    flex-direction: column;
  }
  .qsj-editor-top{
    flex-direction: column-reverse;
  }
  .qsj-editor-right{
    flex-direction: inherit;
  }
  .qsj-editor-left{
    flex-direction: row-reverse;
  }
  .qsj-editor-input{
    min-height:.5rem;
    max-height: 1.5rem;
    overflow: hidden;
    width: 100%;
    flex-shrink: 1;
   /* line-height:.5rem;*/
    font-size: 0.32rem;
    flex-wrap: wrap;
    word-wrap: break-word;
    word-break:break-word;
    white-space: pre-wrap;
    overflow-x: hidden;
    cursor: pointer;
  }
  .qsj-editor-input:empty::after{
    content: attr(placeholder);
    color: #b2b2b2;
    font-size: 0.28rem;
  }
  .qsj-editor-input:focus::before{
    content: none;
  }
  .qsj-counter{
    color: #B2B2B2;
    text-align: right;
    font-size:.28rem;
    /*line-height: .1rem;*/
    flex-shrink: 0;
  }
  .qsj-editor br[tag='qsj_add']{
    display: none!important;
  }
  .qsj-editor br[tag='qsj_br']{
    display: none!important;
  }
  .qsj-editor .qsjWaring{
    color: #f74c31;
  }
</style>
